package com.wxzz.elearning.common.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

public class HttpRequest {

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

    private static String BOUNDARY = "<calculated when request is sent>";

    public static String sendFileReq(String url, MultipartFile multipartFile, String encoding) throws IOException {

        URL sendUrl = new URL(url);
        HttpURLConnection httpConn = (HttpURLConnection) sendUrl.openConnection();
        httpConn.setConnectTimeout(3000); // 设置发起连接的等待时间，3s
        httpConn.setReadTimeout(30000); // 设置数据读取超时的时间，30s
        httpConn.setUseCaches(false); // 设置不使用缓存
        httpConn.setDoOutput(true);
        httpConn.setRequestMethod("PUT");

        httpConn.setRequestProperty("Connection", "Keep-Alive");
        httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
        httpConn.setRequestProperty("Content-Type", "video/mp4");
        OutputStream os = httpConn.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(os);

        String content = "--" + BOUNDARY + "\r\n";
        content       += "Content-Disposition: form-data;  ";
        content       += "我是put数据的值";
        content       += "\r\n--" + BOUNDARY + "\r\n";
        content       += "Content-Type: video/mp4\r\n\r\n";
        bos.write(content.getBytes());

        // 开始写出文件的二进制数据
        FileInputStream fin = new FileInputStream(FileUtil.toFile(multipartFile));
        BufferedInputStream bfi = new BufferedInputStream(fin);
        byte[] buffer = new byte[4096];
        int bytes = bfi.read(buffer, 0, buffer.length);
        while (bytes != -1) {
            bos.write(buffer, 0, bytes);
            bytes = bfi.read(buffer, 0, buffer.length);
        }
        bfi.close();
        fin.close();
        bos.write(("\r\n--" + BOUNDARY).getBytes());
        bos.flush();
        bos.close();
        os.close();

        // 读取返回数据
//        StringBuffer strBuf = new StringBuffer();
//        BufferedReader reader = new BufferedReader(new InputStreamReader(
//                httpConn.getInputStream()));
//        String line = null;
//        while ((line = reader.readLine()) != null) {
//            strBuf.append(line).append("\n");
//        }
//        String res = strBuf.toString();
//        System.out.println(res);
//        reader.close();
        httpConn.disconnect();
        return null;
    }


    public static String sendFileReq(String url, File file, String encoding) throws IOException {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setContentType(ContentType.MULTIPART_FORM_DATA);

        //builder.addBinaryBody("video_upload_url",file);

//        ContentType contentType = ContentType.create("text/plain","utf-8");
        ContentType contentType = ContentType.create(ContentType.MULTIPART_FORM_DATA.getMimeType(), StandardCharsets.UTF_8);
        StringBody stringBody = new StringBody("发送文件",contentType);

        builder.addPart("userName",stringBody);
        String body = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPut httpPut = new HttpPut (url);
        //设置请求参数
        HttpEntity httpEntity = builder.build();
        httpPut.setEntity(httpEntity);
        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPut);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;
    }

    public static void main(String[] args) {
        String url = "https://vod-bucket-86-cn-north-4.obs.cn-north-4.myhuaweicloud.com:443/0bbc3b0cbb8026fa2f9fc00f222d3fb9/cc75e64431cf71a465f9142f6f34abe0/f3cd85422f34949c7bd3a41ba8cad765.mp4?AWSAccessKeyId=MZH0LUL329N1SSXNB3S4&Expires=1618570004&Signature=zOuNJSldbsMuk1g%2Fv%2BMkVKOV%2FoI%3D";

        File attach_file = new File("C:\\Users\\zhangjunjie\\Videos\\Captures\\League of Legends (TM) Client 2020-10-31 11-34-57.mp4");

        try {
            String result1 = sendFileReq (url, attach_file, "utf-8");
            System.out.println (result1);

        } catch (Exception e) {
            e.printStackTrace ( );
        }
    }


}
